const https = require("https");
const he = require('he');

function Get(url, option) {
    return new Promise((resolve, reject) => {
        https.get(url, option, (res) => {
            let data = "";
            res.on('data', (chunk) => {
                data += chunk;
            });
            res.on("end", () => {
                resolve(data);
            })
        }).on("error", (e) => {
            reject(e);
        });
    })
}

async function start() {
    // 搜索歌曲，过滤出 Song_id 
    let song_name = "My Love";
    let singer = "Westlife";
    let album = "Coast To Coast (Expanded Edition)";
    let Song_id = null;
    let Songmid = null;
    const url1 = "https://c.y.qq.com/soso/fcgi-bin/music_search_new_platform?searchid=53806572956004615&t=1&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=50&w="+song_name;
    const options1 = { method: 'GET' }
    data = await Get(url1, options1);
    const jsonRegex = /^.*?\((.*)\)$/;
    const match1 = data.match(jsonRegex);
    if (match1 && match1[1]) {
        const songs = JSON.parse(match1[1]).data.song.list;        
        for(let i = 0; i < songs.length; i++){
            let segs = songs[i].f.split("|");
            // console.log(songs[i].f);
            
            if(segs && segs[3] && segs[5] && (he.decode(segs[3]).includes(singer)) && (he.decode(segs[5]) === album)){
                Song_id = segs[0];
                // console.log(Song_id);
                break;
            }
        }
        if(null === Song_id){
            for(let i = 0; i < songs.length; i++){
                let segs = songs[i].f.split("|");
                if(segs && segs[3] && (he.decode(segs[3]).includes(singer))){
                    Song_id = segs[0];
                    // console.log(Song_id);
                    break;
                }
            }
        }
    }

    if(null === Song_id){
        console.log("no lrc found");
        return;
    }

    // 获取 Songmid
    const url2 = "https://c.y.qq.com/v8/fcg-bin/fcg_play_single_song.fcg?songid=" + Song_id +"&tpl=yqq_song_detail&format=jsonp&callback=getOneSongInfoCallback";
    const options2 = { method: 'GET' }
    data = await Get(url2, options2);
    const match2 = data.match(jsonRegex);
    if (match2 && match2[1]) {
        Songmid = JSON.parse(match2[1]).data[0].mid;
        // console.log(Songmid);
    }
    
    // 获取歌词
    const url3 = "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?songmid=" + Songmid + "&format=json&nobase64=1";
    const options3 = {
        method: 'GET',
        headers: {
          'Referer': 'https://y.qq.com/portal/player.html'
        }
    };
    data = await Get(url3, options3);
    console.log(JSON.parse(data).lyric);
}

start();